package raft

import (
	"sync"
	"time"
)

type DownLatch struct {
	wg sync.WaitGroup
}

func newDownLatch(count int) *DownLatch {
	latch := &DownLatch{}
	latch.wg.Add(count)
	return latch
}

func (latch *DownLatch) Down() {
	latch.wg.Done()
}

func (latch *DownLatch) Wait() {
	latch.wg.Wait()
}

func (latch *DownLatch) WaitTime(t time.Duration) {
	waitCh := make(chan struct{})
	go func() {
		latch.wg.Wait()
		close(waitCh)
	}()
	select {
	case <-waitCh:
		return
	case <-time.After(t):
		return
	}
}
